package com.fr.lintcode;

import org.junit.Test;

/**
*作者：furong
*日期：2017年1月6日
*时间：下午6:53:39
*/
public class Q180 {
    /**
     *@param n: Given a decimal number that is passed in as a string
     *@return: A string
     */
    public String binaryRepresentation(String n) {
        if (n == null || n.length() == 0) {
            return "ERROR";
        }
        String s[] = n.split("\\.");
        if (s.length == 1) {
            return Long.toBinaryString(Long.parseLong(s[0]));
        }
        String rs = Long.toBinaryString(Long.parseLong(s[0]));
        double a = Double.parseDouble("0." + s[1]);
        if (a == 0) {
            return rs;
        }
        rs += ".";
        StringBuffer sb = new StringBuffer();
        while (a > 0 && sb.length() < 32) {
            a = a * 2;
            if (a >= 1) {
                sb.append("1");
                a = a - 1;
            } else {
                sb.append("0");
            }
        }
        if (a == 0) {
            return rs + sb.toString();
        } else {
            return "ERROR";
        }
    }

    @Test
    public void testA() {
        System.out.println(binaryRepresentation("3.8"));
    }
}
